/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent.locks;
import java.util.concurrent.TimeUnit;
import java.util.Collection;

/**
 * 一个可重入互斥{@link Lock}, 具有与使用{@code synchronized}方法
 * 和语句访问的隐式监视器锁相同的基本行为和语义, 但具有扩展功能.
 *
 * <p>一个{@code ReentrantLock}是由上次成功锁定但尚未解锁的线程所<em>拥有的</em>.
 * 当该锁不属于另一个线程时, 调用{@code lock}的线程将返回被成功获取该锁. 如果当前线程
 * 已经拥有了锁, 则该方法将立即返回. 这可以使用方法{@link #isHeldByCurrentThread}
 * 和{@link #getHoldCount}进行检查.
 *
 * <p>此类的构造函数接受一个可选的<em>fairness</em>参数. 当设置{@code true}
 * 时, 在争用下, 锁定有利于授予对等待时间最长线程的访问权限. 否则, 此锁不保证任何
 * 特定的访问顺序. 使用由许多线程访问的公平锁的程序可能显示出比使用默认设置的程序
 * 更低的总体吞吐量(即, 更慢; 通常慢得多), 但获得锁的时间差异较小, 并保证不会出现
 * 饥饿. 但是, 请注意, 锁的公平性并不能保证线程调度的公平性. 因此, 使用公平锁的
 * 许多线程中的一个线程可以连续多次获得它, 而其他活动想检查没有进行并且当前没有
 * 持有该锁.
 * 还要注意, 不计时的{@link #tryLock()}方法不尊重公平性设置, 如果锁可用,
 * 即使其他线程正在等待, 它也会成功.
 *
 * <p>建议<em>始终</em>在调用 {@code lock}之后立即使用{@code try}块,
 * 最常见的是在构造之前/之后, 例如:
 *
 *  <pre> {@code
 * class X {
 *   private final ReentrantLock lock = new ReentrantLock();
 *   // ...
 *
 *   public void m() {
 *     lock.lock();  // 阻塞, 直到条件成立
 *     try {
 *       // ... method body
 *     } finally {
 *       lock.unlock()
 *     }
 *   }
 * }}</pre>
 *
 * <p>除了实现{@link Lock}接口之外, 这个类还定义了许多用于检查锁状态的
 * {@code public}和{@code protected}方法. 其中一些方法仅适用于仪表和监测.
 *
 * <p>此类的序列化行为与内置锁相同:
 * 反序列化的锁处于unlock状态, 而与序列化时的状态无关.
 *
 * <p>此锁最多支持同一线程的2147483647递归锁. 试图超过这个限制会导致lock
 * 方法的{@link Error}异常.
 *
 * @since 1.5
 * @author Doug Lea
 */
public class ReentrantLock implements Lock, java.io.Serializable {
    private static final long serialVersionUID = 7373984872572414699L;
    /** 提供所有实施机制的同步器 */
    private final Sync sync;

    /**
     * 此锁的同步控制的基础. 分为以下公平和非公平版本.
     * 使用AQS状态表示锁上的挂起次数.
     */
    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;

        /**
         * 执行{@link Lock#lock}.
         * 子类化的主要原因是允许非公平版本的快速路径.
         */
        abstract void lock();

        /**
         * 执行非公平tryLock.  tryAcquire在子类中实现,
         * 但两者都需要tryLock方法的非公平尝试.
         */
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;
        }

        protected final boolean isHeldExclusively() {
            // 虽然我们通常必须在所有者之前读取状态, 但我们不需要这样做来检查当前线程是否为所有者
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

        final ConditionObject newCondition() {
            return new ConditionObject();
        }

        // 方法从外部类中继

        final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

        final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

        final boolean isLocked() {
            return getState() != 0;
        }

        /**
         * 从stream重新构造实例(即反序列化).
         */
        private void readObject(java.io.ObjectInputStream s)
                throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // 重置至unlocked状态
        }
    }

    /**
     * 非公平锁的同步对象
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * 执行lock.
         * 尝试立即barge, 故障时回退到正常获取.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

    /**
     * 公平锁的同步对象
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        /**
         * tryAcquire的公平版本. 除非地柜调用或没有等待程序, 否则不要授予访问权限.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                        compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
    }

    /**
     * 创建一个新的{@code ReentrantLock}的实例.
     * 这相当于使用{@code ReentrantLock(false)}.
     */
    public ReentrantLock() {
        sync = new NonfairSync();
    }

    /**
     * 使用给定的公平策略创建{@code ReentrantLock}的实例.
     *
     * @param fair {@code true} 如果该锁应使用公平排序策略
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

    /**
     * 获取锁.
     *
     * <p>如果锁没有被另一个线程持有, 则获取锁, 并立即返回, 将锁持有计数设置为1.
     *
     * <p>如果当前线程已经持有锁, 那么持有计数将增加1, 并且该方法立即返回.
     *
     * <p>如果锁由另一个线程持有, 则当前线程处于线程调度目的而被禁用并且处于休眠
     * 状态, 直到获取了锁为止, 此时锁持有计数被设置为1.
     */
    public void lock() {
        sync.lock();
    }

    /**
     * 获取锁, 除非当前线程是{@linkplain Thread#interrupt interrupted}.
     *
     * <p>如果锁未被其他线程持有, 则获取该锁并立即return, 并将锁持有计数设置为1.
     *
     * <p>如果当前线程已经持有此锁, 则持有计数增加1, 并且该方法立即return.
     *
     * <p>如果锁由另一个线程持有, 那么当前线程将因线程调度目的而被禁用, 并处于
     * 休眠状态, 知道发生以下两种情况之一:
     *
     * <ul>
     *
     * <li>锁由当前线程获取; or
     *
     * <li>其他线程{@linkplain Thread#interrupt interrupts}当前线程.
     *
     * </ul>
     *
     * <p>如果锁是由当前线程获取的, 则锁持有计数设置为1.
     *
     * <p>如果当前线程:
     *
     * <ul>
     *
     * <li>在进入此方法时设置其中断状态; or
     *
     * <li>在获取锁时时{@linkplain Thread#interrupt interrupted},
     *
     * </ul>
     *
     * 然后抛出{@link InterruptedException}, 清除当前线程的中断状态.
     *
     * <p>在这个实现中, 由于该方法是一个显式中断点, 因此优先考虑响应中断,
     * 而不是正常或可冲入获取锁.
     *
     * @throws InterruptedException 如果当前线程被中断
     */
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    /**
     * 仅在调用时未被其他线程持有时获取锁.
     *
     * <p>如果锁未被其他线程持有, 则获取该锁, 并立即返回{@code true}, 将锁持有计数
     * 设置为1. 即使将此锁设置为使用公平排序策略, 如果锁可用, 无论当前是否有其他线程
     * 正在等待该锁, 对{@code tryLock()}的调用都<em>将</em>立即获取该锁. 这种
     * "barging"行为在某些情况下是有用的, 即使它破坏了公平. 如果希望遵守此锁的公平性
     * 设置, 那么使用{@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) },
     * 这几乎是等效的(它还可以检测中断).
     *
     * <p>如果当前线程已经持有此锁, 则持有计数增加1, 该方法返回{@code true}.
     *
     * <p>如果锁由另一个线程持有, 那么这个方法将立即返回值{@code false}.
     *
     * @return {@code true} 如果锁是空闲的并且被当前线程获取, 或者锁已经被
     *         当前线程持有; 否则为{@code false}
     */
    public boolean tryLock() {
        return sync.nonfairTryAcquire(1);
    }

    /**
     * 如果该锁咋给定的等待时间内没有被其他线程持有, 并且当前线程还没有被
     * {@linkplain Thread#interrupt interrupted}, 则获取该锁.
     *
     * <p>如果锁未被其他线程持有, 则获取该锁, 并立即返回值{@code true}, 将持有
     * 计数设置为1. 如果将此锁设置为使用公平排序策略, 那么如果有任何其他线程正在等待
     * 该锁, 则<em>将不会</em>获取可用的锁. 这与{@link #tryLock()}方法形成对比.
     * 如果你想要一个允许闯入公平锁的定时{@code tryLock}, 那么将定时和非定时形式
     * 结合在一起:
     *
     *  <pre> {@code
     * if (lock.tryLock() ||
     *     lock.tryLock(timeout, unit)) {
     *   ...
     * }}</pre>
     *
     * <p>如果当前已经持有此锁, 则持有计数增加1, 该方法返回{@code true}.
     *
     * <p>如果锁由另一个线程持有, 那么当前线程将因线程调度目的而被禁用, 并处于
     * 休眠状态, 知道发生以下三种情况之一:
     *
     * <ul>
     *
     * <li>锁由当前线程获取; or
     *
     * <li>其他线程{@linkplain Thread#interrupt interrupts}当前线程; or
     *
     * <li>指定的等待时间已过
     *
     * </ul>
     *
     * <p>如果获得了锁, 则返回值{@code true}, 并将锁持有计数设置为1.
     *
     * <p>如果当前线程:
     *
     * <ul>
     *
     * <li>在进入此方法时是否设置了中断状态; or
     *
     * <li>在获取锁时是{@linkplain Thread#interrupt interrupted},
     *
     * </ul>
     * 然后抛出{@link InterruptedException}, 并清除当前线程的中断状态.
     *
     * <p>If the specified waiting time elapses then the value {@code false}
     * is returned.  If the time is less than or equal to zero, the method
     * will not wait at all.
     *
     * <p>In this implementation, as this method is an explicit
     * interruption point, preference is given to responding to the
     * interrupt over normal or reentrant acquisition of the lock, and
     * over reporting the elapse of the waiting time.
     *
     * @param timeout the time to wait for the lock
     * @param unit the time unit of the timeout argument
     * @return {@code true} if the lock was free and was acquired by the
     *         current thread, or the lock was already held by the current
     *         thread; and {@code false} if the waiting time elapsed before
     *         the lock could be acquired
     * @throws InterruptedException 如果当前线程被中断
     * @throws NullPointerException if the time unit is null
     */
    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

    /**
     * Attempts to release this lock.
     *
     * <p>If the current thread is the holder of this lock then the hold
     * count is decremented.  If the hold count is now zero then the lock
     * is released.  If the current thread is not the holder of this
     * lock then {@link IllegalMonitorStateException} is thrown.
     *
     * @throws IllegalMonitorStateException if the current thread does not
     *         hold this lock
     */
    public void unlock() {
        sync.release(1);
    }

    /**
     * Returns a {@link Condition} instance for use with this
     * {@link Lock} instance.
     *
     * <p>The returned {@link Condition} instance supports the same
     * usages as do the {@link Object} monitor methods ({@link
     * Object#wait() wait}, {@link Object#notify notify}, and {@link
     * Object#notifyAll notifyAll}) when used with the built-in
     * monitor lock.
     *
     * <ul>
     *
     * <li>If this lock is not held when any of the {@link Condition}
     * {@linkplain Condition#await() waiting} or {@linkplain
     * Condition#signal signalling} methods are called, then an {@link
     * IllegalMonitorStateException} is thrown.
     *
     * <li>When the condition {@linkplain Condition#await() waiting}
     * methods are called the lock is released and, before they
     * return, the lock is reacquired and the lock hold count restored
     * to what it was when the method was called.
     *
     * <li>If a thread is {@linkplain Thread#interrupt interrupted}
     * while waiting then the wait will terminate, an {@link
     * InterruptedException} will be thrown, and the thread's
     * interrupted status will be cleared.
     *
     * <li> Waiting threads are signalled in FIFO order.
     *
     * <li>The ordering of lock reacquisition for threads returning
     * from waiting methods is the same as for threads initially
     * acquiring the lock, which is in the default case not specified,
     * but for <em>fair</em> locks favors those threads that have been
     * waiting the longest.
     *
     * </ul>
     *
     * @return the Condition object
     */
    public Condition newCondition() {
        return sync.newCondition();
    }

    /**
     * Queries the number of holds on this lock by the current thread.
     *
     * <p>A thread has a hold on a lock for each lock action that is not
     * matched by an unlock action.
     *
     * <p>The hold count information is typically only used for testing and
     * debugging purposes. For example, if a certain section of code should
     * not be entered with the lock already held then we can assert that
     * fact:
     *
     *  <pre> {@code
     * class X {
     *   ReentrantLock lock = new ReentrantLock();
     *   // ...
     *   public void m() {
     *     assert lock.getHoldCount() == 0;
     *     lock.lock();
     *     try {
     *       // ... method body
     *     } finally {
     *       lock.unlock();
     *     }
     *   }
     * }}</pre>
     *
     * @return the number of holds on this lock by the current thread,
     *         or zero if this lock is not held by the current thread
     */
    public int getHoldCount() {
        return sync.getHoldCount();
    }

    /**
     * Queries if this lock is held by the current thread.
     *
     * <p>Analogous to the {@link Thread#holdsLock(Object)} method for
     * built-in monitor locks, this method is typically used for
     * debugging and testing. For example, a method that should only be
     * called while a lock is held can assert that this is the case:
     *
     *  <pre> {@code
     * class X {
     *   ReentrantLock lock = new ReentrantLock();
     *   // ...
     *
     *   public void m() {
     *       assert lock.isHeldByCurrentThread();
     *       // ... method body
     *   }
     * }}</pre>
     *
     * <p>It can also be used to ensure that a reentrant lock is used
     * in a non-reentrant manner, for example:
     *
     *  <pre> {@code
     * class X {
     *   ReentrantLock lock = new ReentrantLock();
     *   // ...
     *
     *   public void m() {
     *       assert !lock.isHeldByCurrentThread();
     *       lock.lock();
     *       try {
     *           // ... method body
     *       } finally {
     *           lock.unlock();
     *       }
     *   }
     * }}</pre>
     *
     * @return {@code true} if current thread holds this lock and
     *         {@code false} otherwise
     */
    public boolean isHeldByCurrentThread() {
        return sync.isHeldExclusively();
    }

    /**
     * Queries if this lock is held by any thread. This method is
     * designed for use in monitoring of the system state,
     * not for synchronization control.
     *
     * @return {@code true} if any thread holds this lock and
     *         {@code false} otherwise
     */
    public boolean isLocked() {
        return sync.isLocked();
    }

    /**
     * Returns {@code true} if this lock has fairness set true.
     *
     * @return {@code true} if this lock has fairness set true
     */
    public final boolean isFair() {
        return sync instanceof FairSync;
    }

    /**
     * Returns the thread that currently owns this lock, or
     * {@code null} if not owned. When this method is called by a
     * thread that is not the owner, the return value reflects a
     * best-effort approximation of current lock status. For example,
     * the owner may be momentarily {@code null} even if there are
     * threads trying to acquire the lock but have not yet done so.
     * This method is designed to facilitate construction of
     * subclasses that provide more extensive lock monitoring
     * facilities.
     *
     * @return the owner, or {@code null} if not owned
     */
    protected Thread getOwner() {
        return sync.getOwner();
    }

    /**
     * Queries whether any threads are waiting to acquire this lock. Note that
     * because cancellations may occur at any time, a {@code true}
     * return does not guarantee that any other thread will ever
     * acquire this lock.  This method is designed primarily for use in
     * monitoring of the system state.
     *
     * @return {@code true} if there may be other threads waiting to
     *         acquire the lock
     */
    public final boolean hasQueuedThreads() {
        return sync.hasQueuedThreads();
    }

    /**
     * Queries whether the given thread is waiting to acquire this
     * lock. Note that because cancellations may occur at any time, a
     * {@code true} return does not guarantee that this thread
     * will ever acquire this lock.  This method is designed primarily for use
     * in monitoring of the system state.
     *
     * @param thread the thread
     * @return {@code true} if the given thread is queued waiting for this lock
     * @throws NullPointerException if the thread is null
     */
    public final boolean hasQueuedThread(Thread thread) {
        return sync.isQueued(thread);
    }

    /**
     * Returns an estimate of the number of threads waiting to
     * acquire this lock.  The value is only an estimate because the number of
     * threads may change dynamically while this method traverses
     * internal data structures.  This method is designed for use in
     * monitoring of the system state, not for synchronization
     * control.
     *
     * @return the estimated number of threads waiting for this lock
     */
    public final int getQueueLength() {
        return sync.getQueueLength();
    }

    /**
     * Returns a collection containing threads that may be waiting to
     * acquire this lock.  Because the actual set of threads may change
     * dynamically while constructing this result, the returned
     * collection is only a best-effort estimate.  The elements of the
     * returned collection are in no particular order.  This method is
     * designed to facilitate construction of subclasses that provide
     * more extensive monitoring facilities.
     *
     * @return the collection of threads
     */
    protected Collection<Thread> getQueuedThreads() {
        return sync.getQueuedThreads();
    }

    /**
     * Queries whether any threads are waiting on the given condition
     * associated with this lock. Note that because timeouts and
     * interrupts may occur at any time, a {@code true} return does
     * not guarantee that a future {@code signal} will awaken any
     * threads.  This method is designed primarily for use in
     * monitoring of the system state.
     *
     * @param condition the condition
     * @return {@code true} if there are any waiting threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    public boolean hasWaiters(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns an estimate of the number of threads waiting on the
     * given condition associated with this lock. Note that because
     * timeouts and interrupts may occur at any time, the estimate
     * serves only as an upper bound on the actual number of waiters.
     * This method is designed for use in monitoring of the system
     * state, not for synchronization control.
     *
     * @param condition the condition
     * @return the estimated number of waiting threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    public int getWaitQueueLength(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns a collection containing those threads that may be
     * waiting on the given condition associated with this lock.
     * Because the actual set of threads may change dynamically while
     * constructing this result, the returned collection is only a
     * best-effort estimate. The elements of the returned collection
     * are in no particular order.  This method is designed to
     * facilitate construction of subclasses that provide more
     * extensive condition monitoring facilities.
     *
     * @param condition the condition
     * @return the collection of threads
     * @throws IllegalMonitorStateException if this lock is not held
     * @throws IllegalArgumentException if the given condition is
     *         not associated with this lock
     * @throws NullPointerException if the condition is null
     */
    protected Collection<Thread> getWaitingThreads(Condition condition) {
        if (condition == null)
            throw new NullPointerException();
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
            throw new IllegalArgumentException("not owner");
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
    }

    /**
     * Returns a string identifying this lock, as well as its lock state.
     * The state, in brackets, includes either the String {@code "Unlocked"}
     * or the String {@code "Locked by"} followed by the
     * {@linkplain Thread#getName name} of the owning thread.
     *
     * @return a string identifying this lock, as well as its lock state
     */
    public String toString() {
        Thread o = sync.getOwner();
        return super.toString() + ((o == null) ?
                "[Unlocked]" :
                "[Locked by thread " + o.getName() + "]");
    }
}
